//
//  MAPYManager.swift
//  Mars Proxy
//
//  Created by PowerfullClean on 2023/10/16.
//

import UIKit
import CoreData
import NetworkExtension
import CoreLocation
import Alamofire

@objc protocol MAPYManagerDelegate: NSObjectProtocol {
    @objc optional func mapy_iPScanFinish(mapy_model: MAPYIPScanModel?)
    @objc optional  func mapy_downloadFinish(mapy_value: String)
    @objc optional func mapy_upLoadFinish(mapy_value: String)
    @objc optional func mapy_pingFinish(mapy_ping: String, mapy_jitter: String, mapy_loss: String)
}

class MAPYManager: NSObject {
    @objc static let mapy_manager = MAPYManager()
    override init() {
        super.init()
        
        mapy_addVPNChangeNoti()
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(mapy_enterActive),
            name: UIApplication.didBecomeActiveNotification, object: nil)
        
        mapy_pathMonitor.start(queue: DispatchQueue.global())
        mapy_pathMonitor.pathUpdateHandler = { path in
            DispatchQueue.main.async {
                if path.status == .satisfied {
                    if path.usesInterfaceType(.wifi) {
                       
                        self.mapy_netType = .mapy_wifi
                    } else if path.usesInterfaceType(.cellular) {
                        
                        self.mapy_netType = .mapy_cellular
                    }
                } else {
                    self.mapy_netType = .mapy_none
                    
                    MAPYHudCommon.mapy_showMessage("No available network", isError: false)
                }
            }
        }
    }
    //MARK: - mapy save key
    @objc func mapy_saveIntKey(mapy_key: String, mapy_value: NSInteger, mapy_timeID: String = "") {
        UserDefaults.standard.setValue(mapy_value, forKey: mapy_key+mapy_timeID)
        UserDefaults.standard.synchronize()
    }
    @objc func mapy_getIntValue(mapy_key: String, mapy_timeID: String = "") -> NSInteger {
        guard let mapy_value =  UserDefaults.standard.value(forKey: mapy_key+mapy_timeID) as? NSInteger else { return 0 }
        return mapy_value
    }
    
    @objc func mapy_saveSrKey(mapy_key: String, mapy_value: String, mapy_timeID: String = "") {
        UserDefaults.standard.setValue(mapy_value, forKey: mapy_key+mapy_timeID)
        UserDefaults.standard.synchronize()
    }
    @objc func mapy_getSrValue(mapy_key: String, mapy_timeID: String = "") -> String {
        guard let mapy_value =  UserDefaults.standard.value(forKey: mapy_key+mapy_timeID) as? String else { return "" }
        return mapy_value
    }
    //MARK: - mapy setting
    func mapy_switchAppStore()  {
        let mapy_urlString = "itms-apps://itunes.apple.com/cn/app/id\(mapy_appID)?mt=8&action=write-review"
        let url = URL(string: mapy_urlString)
        if #available(iOS 10, *) {
            UIApplication.shared.open(url!, options: [:],
                                      completionHandler: {
                (success) in
            })
        } else {
            UIApplication.shared.openURL(url!)
        }
    }
    func mapy_shareApp(mapy_vc: MAPYBaseViewController?) {
        var activityItems:[Any]?
        let url = URL(string: "https://itunes.apple.com/app/id\(mapy_appID)")
        activityItems = ["Martian Proxy", url!]
        let mapy_activity = UIActivityViewController(activityItems: activityItems!, applicationActivities: nil)
        mapy_activity.excludedActivityTypes = [.saveToCameraRoll, .openInIBooks, .addToReadingList]
        mapy_activity.completionWithItemsHandler = { a, c, r, e in
        }
        mapy_vc?.present(mapy_activity, animated: true)
    }
    //MARK: - mapy lazy
    var mapy_netType: MAPYNetType = .mapy_none
    let mapy_pathMonitor = NWPathMonitor()
    let mapy_appID = "6469494444"
    var mapy_loctionManager = CLLocationManager()
    weak var mapy_delegate:MAPYManagerDelegate?
    let mapy_storeManager =  NSPersistentContainer(name: "MAPYDataBaseModel")
    var mapy_initEntry = true //程序冷启动
    //MARK: - mapy speed ping
    var mapy_pingServe: MAPYPingServe?
    var mapy_pingErr = false
    var mapy_stopDownloadRequest = false
    var mapy_stopUploadRequest = false
    var mapy_downloadRequest:DownloadRequest?
    var mapy_uploadRequest:UploadRequest?
    var mapy_downAddNumber = 0
    var mapy_downloadName: String = "mapy_downloadName"
    var mapy_uploadAddNumber = 0
    var mapy_uploadName: String = "mapy_uploadName"
    var mapy_downloadValue: Double = 0
    var mapy_uploadValue: Double = 0
    var mapy_homeDownloadValue: Double = 0
    var mapy_homeUploadValue: Double = 0
    var mapy_speedType = 0
    //MARK: - mapy vpn
    var mapy_vpnStateClickType: MAPYVPNStateClickType = .mapy_none
    var mapy_vpnCurStateType: MAPYVpnStateType {
        return MAPYVpnStateType(rawValue: mapy_vpnManager?.connection.status.rawValue ?? 0) ?? .mapy_disconnected
    }
    var mapy_curServerModel: MAPYServerModel?
    var mapy_vpnManager:NETunnelProviderManager?
    var mapy_vpnChangeBlock: ((MAPYVpnStateType)->())?
    let pingGroup1 = DispatchGroup()
    let pingQueue1 = DispatchQueue(label: "com.marksproxy.pingqueue1")
    let pingGroup2 = DispatchGroup()
    let pingQueue2 = DispatchQueue(label: "com.marksproxy.pingqueue2")
    var mapy_pingServerDic = [MAPYVPNResServerModel: SwiftyPing]()
    var mapy_best: Bool = false
    var mapy_smart: Bool = false
}

//MARK: - mapy 后台
extension MAPYManager {
    @objc func mapy_enterActive() {
        if (mapy_vpnCurStateType == .mapy_invalid || mapy_vpnCurStateType == .mapy_disconnected) {
            mapy_vpnChangeBlock?(.mapy_invalid)
        }
        
    }
}
